package com.nowoe.core.bean;

import com.nowoe.core.annotation.Component;

import java.io.File;
import java.lang.annotation.Annotation;
import java.net.URL;

/**
 * @author 倚栏听风 2023/9/16 10:39
 * 扫描类
 */
public class ComponentScanner {
    public static void scan(BeanFactory beanFactory, String packageName) throws ClassNotFoundException {
        String name = packageName.replaceAll("\\.", "/");
        URL url = ComponentScanner.class.getClassLoader().getResource(name);
        String path = url.getFile();
        File dir = new File(path);
        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                scan(beanFactory, packageName + "." + file.getName());
            } else {
                String className = packageName + "." + file.getName().replaceAll(".class", "");
                Class<?> aClass = Class.forName(className);
                if (aClass.getAnnotations().length > 0) {
                    if (aClass.isAnnotationPresent(Component.class)) {
                        beanFactory.register(aClass);
                    } else {
                        Annotation[] annotations = aClass.getAnnotations();
                        for (Annotation annotation : annotations) {
                            if (annotation.annotationType().isAnnotationPresent(Component.class)) {
                                beanFactory.register(aClass);
                                break;
                            }
                        }

                    }
                }
            }
        }
    }
}
